<template>
    <div>
        <table-search
            :current-page='table.pages'
            :page-size='table.size'
            :total='table.total'
            @size-change='handleSizeChange'
            @current-change='handleCurrentChange'
        >
            <template #search>
                <el-row :gutter='15' class='clear-both'>
                    <el-col :span='24'>
                        <card-list title='高级搜索' type='keyvalue' :show-header='true'>
                            <template #btn>
                                <el-button-group>
                                    <el-button icon='elIconSearch' size='mini' @click='submit'>搜索</el-button>
                                </el-button-group>
                            </template>
                            <template #keyvalue>
                                <el-form ref='refForm' class='card-list-form' :model='form' :rules='rules' size='mini'>
                                    <el-row :gutter='15'>
                                        <card-list-item width='100px' prop='name'>
                                            <template #key>委托单位名称</template>
                                            <template #value>
                                                <el-input v-model='form.client' placeholder='请输入委托单位名称'/>
                                            </template>
                                        </card-list-item>
                                    </el-row>
                                </el-form>
                            </template>
                        </card-list>
                    </el-col>
                </el-row>
            </template>
            <el-table
                ref='filterTable'
                row-key='id'
                highlight-current-row
                border
                :data='tableData.records'
                style='width: 100%;'
            >
                <el-table-column prop='id' label='id' width='100'/>
                <el-table-column prop='user' label='用户名' column-key='client'/>
                <el-table-column prop='role' label='权限' column-key='role'/>
                <el-table-column prop='client' label='所属委托单位' column-key='client' v-action='["admin","client_admin"]'/>
                <el-table-column prop='check' label='所属检测站' column-key='client' v-action='["admin","check_admin"]'/>
                <el-table-column prop='createTime' label='创建时间'/>
                <el-table-column prop='updateTime' label='更新时间'/>
                <el-table-column prop='action' label='操作' width='200' v-action='"client_admin"'>
                    <template #default='scope'>
                        <el-button size='mini' type='text' @click='bindProjectBindsClick(scope.row)'
                                   v-action='"client_admin"'
                        >绑定项目
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </table-search>

        <el-dialog v-model='dialogTableVisible' :title='`[${checkdData.action.user}] 关联项目`'>
            <!--        style='text-align: left; display: inline-block'-->

            <el-transfer
                v-model='checkdData.rightValue'
                filterable
                filter-placeholder='搜索'
                :titles='["未关联", "已关联"]'
                :button-texts='["取消关联", "关联"]'
                :format='{
                noChecked: "${total}",
                hasChecked: "${checked}/${total}",
            }'
                :data='projectData.records'
                :props='{
                key: "id",
                label: "project"
            }'
                @change='editProjectBinds'
            />
        </el-dialog>
    </div>
</template>

<script lang='ts'>
import { defineComponent, reactive, Ref, ref } from 'vue'
import TableSearch from '/@/components/TableSearch/index.vue'
import CardList from '/@/components/CardList/CardList.vue'
import CardListItem from '/@/components/CardList/CardListItem.vue'
// 网络请求
import { getTableList } from '/@/api/User'
import { getTableList as projectTableList } from '/@/api/Project'
import { validate } from '/@/utils/formExtend'
// table结构
import { IUserTableList } from '/@/type/views/User/UserList'
import { editProjectBindIds, getProjectBindsById } from '/@/api/ProjectBinds'
import { checkPermission } from '/@/utils/permission'

interface ISearchForm {
    client: string
}

// 键值对样式，及表单校验
const search = (table: ITable<IUserTableList>, form: ISearchForm) => {
    const rules = reactive({})
    const refForm = ref(null)
    const submit = async() => {
        if (!await validate(refForm)) return
        table.pages = 1
        await renderTableList(table, form)
    }
    return {
        rules,
        submit,
        refForm
    }
}

const renderTableList = async(table: ITable<IUserTableList>, form: ISearchForm) => {
    const d = await getTableList({ page: table.pages, pageSize: table.size, ...form })
    table.records = d.data.data.records
    table.total = d.data.data.total
}

const tableRender = (table: ITable<IUserTableList>, form: ISearchForm) => {
    renderTableList(table, form)
    const handleSizeChange = (v: number) => (table.size = v) && renderTableList(table, form)
    const handleCurrentChange = (v: number) => (table.pages = v) && renderTableList(table, form)
    return { table, handleSizeChange, handleCurrentChange }
}

const getProjectData = async(projectData) => {
    if (checkPermission(['client_admin', 'admin'], 'or')) {
        const d = await projectTableList({ page: 1, pageSize: 99999 })
        projectData.records = d.data.data.records
    } else {
        projectData.records = []
    }
}

const bindProjectBinds = (checkdData, projectData, dialogTableVisible: Ref) => {
    // 先获取全部数据
    getProjectData(projectData)

    const bindProjectBindsClick = async(row: ICheckTableLis) => {
        // 根据id获取当前已关联
        const d = await getProjectBindsById(row.id)
        checkdData.rightValue = []
        d.data.data.forEach((v) => {
            checkdData.rightValue.push(v.projectId)
        })
        checkdData.action = row
        dialogTableVisible.value = true
    }

    const editProjectBinds = async(ids: Array<number>) => {
        await editProjectBindIds(checkdData.action.id, ids)
    }

    return {
        bindProjectBindsClick,
        editProjectBinds,
        projectData,
        checkdData
    }
}
export default defineComponent({
    name: 'UserList',
    components: {
        TableSearch,
        CardList,
        CardListItem
    },
    setup() {
        const form: ISearchForm = reactive({
            client: ''
        })

        // const
        const tableData: ITable<IUserTableList> = reactive({
            records: [],
            total: 0,
            pages: 1,
            size: 20
        })
        // 所有项目列表
        const projectData: Array<IProjectTableList> = reactive({ records: [] })
        // 点击了的数据
        const checkdData = reactive({ action: {}, rightValue: [] })
        // 弹出层显示状态
        const dialogTableVisible = ref(false)

        return {
            form,
            tableData,
            ...tableRender(tableData, form),
            ...search(tableData, form),
            dialogTableVisible,
            ...bindProjectBinds(checkdData, projectData, dialogTableVisible)
        }
    }
})
</script>
